import router from "@/router";
import { useLoginUserStore } from "@/store/userStore";
import ACCESS_EUM from "@/access/accessEUM";
import CheckAccess from "@/access/checkAccess";
//进入页面前，进行校验
router.beforeEach(async (to, from, next) => {
  //当前登录用户
  const loginUserStore = useLoginUserStore();
  let loginUser = loginUserStore.loginUser;

  //如果之前没有获取过登录信息，才自动登录
  if (!loginUser || loginUser.userRole) {
    //加await是为了等待用户登录成功并获取到值后，再执行操作
    await loginUserStore.fetchLoginUser();
    loginUser = loginUserStore.loginUser;
  }

  //当前登录页面需要的权限
  const needAccess = (to.meta?.access as string) ?? ACCESS_EUM.NOT_LOGIN;
  //如果当前页面不需要登录
  if (needAccess !== ACCESS_EUM.NOT_LOGIN) {
    //如果没登录，跳转到登录页面
    if (
      !loginUser ||
      !loginUser.userRole ||
      loginUser.userRole == ACCESS_EUM.NOT_LOGIN
    ) {
      next(`user/login?redirect=${to.fullPath}`);
    }
    //如果已经登录，判断权限是否足够，如果不足跳转到权限不足页面
    if (!CheckAccess(loginUser, needAccess)) {
      console.log(needAccess);
      console.log(loginUser);
      next("/noAuth");
      return;
    }
  }
  next();
});
